﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using elmah2.core.interfaces;
using elmah2.core.data;
using System.Net.Mail;
using elmah2.core.encoders;

namespace elmah2.Email
{
  public class EmailLogger : IErrorLogger
  {
    public string Name
    {
      get { return "Email"; }
    }

    public bool WriteOnly
    {
      get { return true; }
    }

    private string _server;
    private string[] _sendTo;
    private string _sendFrom;

    public void LogError(Error error)
    {
      if (string.IsNullOrEmpty(_server))
        throw new Exception("Email server not found");

      MailMessage newMessage = new MailMessage();
      newMessage.IsBodyHtml = true;
      foreach (string s in _sendTo) newMessage.To.Add(s);
      newMessage.From = new MailAddress(_sendFrom);
      newMessage.Subject = string.Concat("Error Reported by ", error.ApplicationName);
      newMessage.Body = HtmlEncoder.EncodeString(error);

      SmtpClient client = new SmtpClient(_server);
      client.Send(newMessage);
    }

    public void Init(Dictionary<string, string> config)
    {
      if (!config.ContainsKey("Server"))
        throw new Exception("Server data not found");

      if(!config.ContainsKey("SendTo"))
        throw new Exception("SendTo data not found");

      if (!config.ContainsKey("SendFrom"))
        throw new Exception("SendFrom data not found");

      _server = config["Server"];
      _sendTo = config["SendTo"].Split(new char[] { ';' });
      _sendFrom = config["SendFrom"];
    }

    public bool AddApplication(string name)
    {
      return true;
    }

    public List<Application> GetApplications()
    {
      return null;
    }

    public Application GetApplication(int id)
    {
      return null;
    }

    public ErrorData GetErrors(int p, int size, int? app)
    {
      return null;
    }

    public Error GetError(string id)
    {
      return null;
    }
  }
}
